import React, { useState, useCallback } from "react";
import {
  Tooltip,
  Badge,
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Switch,
  Select,
  Space,
  Spin,
} from "antd";
import {
  Map,
  APILoader,
  ScaleControl,
  ToolBarControl,
  Marker,
  ControlBarControl,
  Geolocation,
} from "@uiw/react-amap";
import {
  CopyOutlined,
  AimOutlined,
  EnvironmentOutlined,
  EditOutlined,
  EyeOutlined,
  // ThermometerOutlined,
  DashboardOutlined,
} from "@ant-design/icons";
import copy from "copy-to-clipboard";
import "./index.less";
import config from "../../config/config";

const { Option } = Select;

const MapMarker = () => {
  const [loading, setLoading] = useState(true);
  const [mousePosition, setMousePosition] = useState(null);
  const [selectedSensor, setSelectedSensor] = useState(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isSettingPosition, setIsSettingPosition] = useState(false);
  const [coordinateFormat, setCoordinateFormat] = useState("decimal");
  const [coordinateSystem, setCoordinateSystem] = useState("GCJ02");
  const [form] = Form.useForm();
  const [zoomLevel, setZoomLevel] = useState(14);
  // ... 其他 state 保持不变
  const [mapInstance, setMapInstance] = useState(null);
  // 定位数据
  const [locationData, setLocationData] = useState();

  // 预设位置点
  const presetLocations = [
    {
      name: "杭州",
      position: [120.1551, 30.2539],
      zoom: 12,
    },
    {
      name: "西湖",
      position: [120.1485, 30.242],
      zoom: 15,
    },
    // 可以添加更多预设位置
  ];

  // 处理地图加载完成
  const handleMapComplete = useCallback((map) => {
    console.log("地图加载完成", map); // 调试用
    if (map) {
      setMapInstance(map);
      setLoading(false); // 确保设置加载状态为 false
      message.success("地图加载完成");
    }
  }, []);

  // 快速定位函数
  const handleQuickLocate = useCallback(
    (location) => {
      if (mapInstance && mapInstance.getMap) {
        try {
          const amap = mapInstance.getMap();
          amap.setZoomAndCenter(location.zoom, location.position);
          message.success(`已定位到${location.name}`);
        } catch (error) {
          console.error("定位错误:", error);
          message.error("定位失败，请稍后重试");
        }
      } else {
        message.error("地图实例未准备好");
      }
    },
    [mapInstance]
  );

  // 添加快速定位控件
  const QuickLocateControl = () => (
    <div className="quick-locate-control">
      <Space direction="vertical">
        {presetLocations.map((location, index) => (
          <Tooltip
            key={index}
            title={`定位到${location.name}`}
            placement="left"
          >
            <Button
              type="primary"
              icon={<AimOutlined />}
              onClick={() => handleQuickLocate(location)}
              className="locate-button"
            >
              {location.name}
            </Button>
          </Tooltip>
        ))}
      </Space>
    </div>
  );

  // 模拟传感器数据
  const [sensors, setSensors] = useState([
    {
      id: 1,
      name: "传感器-01",
      position: [120.1551, 30.2539],
      temperature: 25.6,
      humidity: 65,
      online: true,
    },
    {
      id: 2,
      name: "传感器-02",
      position: [120.1601, 30.2579],
      temperature: 26.2,
      humidity: 62,
      online: false,
    },
  ]);

  // 设置默认地图中心点
  const mapCenter = sensors[0]?.position || [120.1551, 30.2539];

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      const newPosition = [Number(values.longitude), Number(values.latitude)];
      if (selectedSensor) {
        setSensors(
          sensors.map((sensor) =>
            sensor.id === selectedSensor.id
              ? { ...sensor, position: newPosition }
              : sensor
          )
        );
        message.success("位置更新成功");
        setIsModalVisible(false);
        setIsSettingPosition(false);
        form.resetFields();
      }
    } catch (error) {
      message.error("更新位置失败");
    }
  };

  // 度分秒格式转换函数
  const decimalToDMS = (decimal) => {
    const degrees = Math.floor(decimal);
    const minutesDecimal = (decimal - degrees) * 60;
    const minutes = Math.floor(minutesDecimal);
    const seconds = ((minutesDecimal - minutes) * 60).toFixed(2);
    return `${degrees}° ${minutes}' ${seconds}"`;
  };

  // 坐标系转换函数（这里只是示例，实际项目中需要使用专业的坐标转换库）
  const transformCoordinate = (lng, lat, from, to) => {
    // 这里应该使用专业的坐标转换库，如 coordtransform
    // 示例仅返回原始值
    return { lng, lat };
  };

  // 格式化坐标显示
  const formatCoordinate = (lng, lat) => {
    if (coordinateFormat === "dms") {
      return `${decimalToDMS(lng)} E, ${decimalToDMS(lat)} N`;
    }
    return `${lng.toFixed(6)}, ${lat.toFixed(6)}`;
  };

  // 处理坐标复制
  const handleCopyCoordinate = () => {
    if (mousePosition) {
      const coordText = formatCoordinate(
        parseFloat(mousePosition.longitude),
        parseFloat(mousePosition.latitude)
      );
      copy(coordText);
      message.success("坐标已复制到剪贴板！");
    }
  };

  // 处理地图点击
  const handleMapClick = (e) => {
    if (isSettingPosition && selectedSensor) {
      const { lng, lat } = e.lnglat;
      form.setFieldsValue({
        longitude: lng.toFixed(6),
        latitude: lat.toFixed(6),
      });
      message.success("已选择新位置，请点击保存确认");
    }
  };

  // 添加标记点击处理函数
  const handleMarkerClick = (sensor) => {
    setSelectedSensor(sensor);
    setIsModalVisible(true);
    form.setFieldsValue({
      longitude: sensor.position[0],
      latitude: sensor.position[1],
    });
  };

  // 坐标显示组件
  const CoordinateDisplay = () => (
    <div className="coordinate-display">
      <Space>
        <span>
          {mousePosition
            ? formatCoordinate(
                parseFloat(mousePosition.longitude),
                parseFloat(mousePosition.latitude)
              )
            : "-"}
        </span>
        <Button
          type="text"
          icon={<CopyOutlined />}
          onClick={handleCopyCoordinate}
          size="small"
        />
      </Space>
    </div>
  );

  // 坐标控制面板
  const CoordinateControlPanel = () => (
    <div className="coordinate-control-panel">
      <Space>
        <Select
          value={coordinateFormat}
          onChange={setCoordinateFormat}
          size="small"
          style={{ width: 120 }}
        >
          <Option value="decimal">十进制度</Option>
          <Option value="dms">度分秒</Option>
        </Select>
        <Select
          value={coordinateSystem}
          onChange={setCoordinateSystem}
          size="small"
          style={{ width: 120 }}
        >
          <Option value="WGS84">WGS84</Option>
          <Option value="GCJ02">GCJ02(火星坐标)</Option>
          <Option value="BD09">BD09(百度坐标)</Option>
        </Select>
      </Space>
    </div>
  );

  // 计算图标大小的函数
  const getMarkerSize = useCallback((zoom) => {
    // 根据缩放级别返回不同的尺寸
    if (zoom >= 17) return 200;
    if (zoom >= 15) return 100;
    if (zoom >= 13) return 50;
    return 30;
  }, []);

  // 使用 useCallback 和防抖来优化缩放处理
  const handleZoomChange = useCallback(
    (e) => {
      const newZoom = Math.round(e.target.getZoom());
      // 只在缩放级别实际改变时更新状态
      if (newZoom !== zoomLevel) {
        message.info(newZoom);
        setZoomLevel(newZoom);
      }
    },
    [zoomLevel]
  );

  // 自定义 Marker 内容
  const markerContent = (sensor) => (
    <Tooltip
      title={
        <div className="marker-tooltip">
          <div className="tooltip-header">
            <h4>{sensor.name}</h4>
            <Badge
              status={sensor.online ? "success" : "error"}
              text={sensor.online ? "在线" : "离线"}
            />
          </div>

          <div className="tooltip-content">
            <div className="sensor-stats">
              <div className="stat-item">
                <span className="label">温度</span>
                <span className="value">{sensor.temperature}°C</span>
              </div>
              <div className="stat-item">
                <span className="label">湿度</span>
                <span className="value">{sensor.humidity}%</span>
              </div>
            </div>

            <div className="sensor-location">
              <div className="location-item">
                <span className="label">经度：</span>
                <span className="value">{sensor.position[0]}</span>
              </div>
              <div className="location-item">
                <span className="label">纬度：</span>
                <span className="value">{sensor.position[1]}</span>
              </div>
            </div>
          </div>

          <div className="tooltip-actions">
            <Button
              type="link"
              size="small"
              onClick={(e) => {
                e.stopPropagation();
                handleMarkerClick(sensor);
              }}
            >
              编辑位置
            </Button>
          </div>
        </div>
      }
      color="#1a4a8d"
      placement="top"
      overlayClassName="marker-tooltip-overlay"
    >
      <div
        className={`custom-marker ${sensor.online ? "online" : "offline"}`}
        onClick={() => handleMarkerClick(sensor)}
      >
        <Badge status={sensor.online ? "success" : "error"} offset={[-3, 3]}>
          <img
            src={sensor.online ? "/online.png" : "/offline.png"}
            alt={sensor.online ? "在线" : "离线"}
            className="marker-icon"
            style={{
              width: `${getMarkerSize(zoomLevel)}px`,
              height: `${getMarkerSize(zoomLevel)}px`,
              objectFit: "contain",
              transition: "width 0.3s, height 0.3s", // 添加平滑过渡效果
            }}
          />
        </Badge>
        <div className="marker-label">{sensor.name}</div>
      </div>
    </Tooltip>
  );

  return (
    <div className="map-marker-container">
      <Card title="地图展示" className="map-card">
        <APILoader
          akay={config.mapConfig.akey}
          version={config.mapConfig.version}
          protocol="https"
          // 确保包含所有需要的插件
          plugin={[
            "AMap.Scale",
            "AMap.ToolBar",
            "AMap.ControlBar",
            "AMap.Geolocation",
            "AMap.GeometryUtil",
          ]}
        >
          <div style={{ height: "500px", position: "relative" }}>
            <Map
              zoom={14}
              center={mapCenter}
              onComplete={handleMapComplete}
              onError={(error) => {
                console.error("地图加载错误:", error);
                message.error("地图加载失败");
                setLoading(false);
              }}
              
              onMouseMove={(e) => {
                if (e && e.lnglat) {
                  setMousePosition({
                    longitude: e.lnglat.lng,
                    latitude: e.lnglat.lat,
                  });
                }
              }}
              onZoomChange={handleZoomChange}
              onClick={handleMapClick}
            >
              {!loading && (
                <>
                  {sensors.map((sensor) => (
                    <Marker
                      key={sensor.id}
                      position={sensor.position}
                      offset={[-16, -16]}
                      visiable={true}
                    >
                      {markerContent(sensor)}
                    </Marker>
                  ))}
                  <ToolBarControl offset={[16, 10]} position="RB" />
                  <ScaleControl offset={[16, 30]} position="LB" />

                  {/* <Geolocation
                    maximumAge={10000}
                    enableHighAccuracy={true}
                    timeout={5000}
                    buttonPosition="RB"
                    offset={[16, 80]}
                    zoomToAccuracy={true}
                    showCircle={true}
                    panToLocation={true}
                    onComplete={(data) => {
                      console.log("定位成功:", data);
                      message.success("定位成功");
                      setLocationData(data);
                    }}
                    onError={(error) => {
                      console.error("定位失败:", error);
                      message.error("定位失败，请检查定位权限");
                      setLocationData(null);
                    }}
                  /> */}

                  <ControlBarControl offset={[16, 180]} position="RB" />
                  <QuickLocateControl />
                </>
              )}
            </Map>

            <CoordinateDisplay />
            <CoordinateControlPanel />
            {loading && (
              <div className="map-loading">
                <Spin tip="地图加载中..." />
              </div>
            )}
            <pre style={{ padding: 10, marginTop: 10 }}>
              {locationData ? JSON.stringify(locationData, null, 2) : "{正在获取}"}
            </pre>
          </div>
        </APILoader>
      </Card>

      <Modal
        title="修改设备坐标"
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          setIsSettingPosition(false);
          form.resetFields();
        }}
        footer={null}
      >
        <Form form={form} onFinish={handleSubmit} layout="vertical">
          <Form.Item>
            <Space>
              <Switch
                checked={isSettingPosition}
                onChange={(checked) => setIsSettingPosition(checked)}
              />
              <span>点击地图选择位置</span>
            </Space>
          </Form.Item>
          <Form.Item
            label="经度"
            name="longitude"
            rules={[
              { required: true, message: "请输入经度" },
              {
                pattern: /^-?((0|1?[0-9]?[0-9]|2[0-3]?[0-9])\.[0-9]*|180\.0*)$/,
                message: "请输入有效的经度值",
              },
            ]}
          >
            <Input placeholder="请输入经度" />
          </Form.Item>
          <Form.Item
            label="纬度"
            name="latitude"
            rules={[
              { required: true, message: "请输入纬度" },
              {
                pattern: /^-?([0-8]?[0-9]\.[0-9]*|90\.0*)$/,
                message: "请输入有效的纬度值",
              },
            ]}
          >
            <Input placeholder="请输入纬度" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MapMarker;
